package com.htudata.core.util.operation;

import java.util.HashMap;
import java.util.Map;

public class UrlOperationUtils {

  
  public static String getUrlWithParam(String url, String urlParam) {
    String result = url;
    if (StringOperationUtils.isValidStr(urlParam))
      result = result + "?" + urlParam; 
    return result;
  }
  
  public static String getUrlWithoutParam(String url) {
    String result = url;
    int index = url.indexOf("?");
    if (index == -1)
      return result; 
    result = url.substring(0, index);
    return result;
  }
  
  public static String getUrlParamFromUrl(String url) {
    int index = url.indexOf("?");
    if (index == -1)
      return ""; 
    String result = url.substring(index + 1);
    return result;
  }
  
  public static Map<String, String> getUrlParamMap(String url) {
    String tempUrl = getUrlParamFromUrl(url);
    String[] tempUrlArr = tempUrl.split("&");
    Map<String, String> result = new HashMap<>();
    for (String temp : tempUrlArr) {
      String[] tempParamArr = temp.split("=");
      String paramName = tempParamArr[0];
      String paramValue = tempParamArr[1];
      result.put(paramName, paramValue);
    } 
    return result;
  }
  
  public static String getUrlParamByMap(Map<String, String> map) {
    if (!MapOperationUtils.isValidMap(map))
      return ""; 
    StringBuffer result = new StringBuffer();
    for (Map.Entry<String, String> entry : map.entrySet())
      result.append("&" + (String)entry.getKey() + "=" + (String)entry.getValue()); 
    StringBufferOperationUtils.replaceFirstChar(result, "?");
    return result.toString();
  }
}
